<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <select-child-bank
          clearable
          v-model="params['bank_id.eq']"
          @change="getAllData()"
          placeholder="贷款银行(可输入过滤)"
        ></select-child-bank>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="queryDate"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="创建日期(含)"
          end-placeholder="创建日期(含)"
          value-format="yyyy-MM-dd"
          @change="handleDateQuery"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="queryDate2"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="放款日期(含)"
          end-placeholder="放款日期(含)"
          value-format="yyyy-MM-dd"
          @change="handleDateQuery2"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="queryDate3"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="到期日期(含)"
          end-placeholder="到期日期(含)"
          value-format="yyyy-MM-dd"
          @change="handleDateQuery3"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <c-select
          v-model="params['is_pro_dir.eq']"
          :options="{
            0: '联担业务',
            1: '省直业务',
          }"
          placeholder="是否省直业务"
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-input
          placeholder="担保机构"
          v-model="params.service_name"
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getAllData()">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="card my-2">
      <div class="card-body" v-loading="countLoading">
        <span class="h5 text-muted">
          项目共计：
          <span class="text-danger">{{ tableCount }}</span>
        </span>
        <span class="h5 text-muted ml-5">
          金额合计：
          <span class="text-danger">{{ tableFunds || '-' }}</span>
          万元
        </span>
      </div>
      <div class="pl-3 pb-3">
        <div class="text-warning">
          查询某月数据，时间范围选择同一个月即可(数据只包含审批完成的项目，审批中项目未统计)
        </div>
        <div class="text-warning">详细数据可以点击表格某一行查看详细数据</div>
      </div>
    </div>

    <c-table
      border
      class="table-sm"
      v-loading="loading"
      :columns="tableColumns"
      :data="tableData"
      @row-click="selectRow"
    ></c-table>

    <normal-detail :visible.sync="viewVisible" :other-params="otherParams"></normal-detail>
  </div>
</template>

<script>
import SelectChildBank from '@/bank/components/select/SelectChildBank'
import { mapGetters } from 'vuex'
import { getAddressNextValue } from '@/common/api/address'
import NormalDetail from '@/bank/views/business/count/NormalDetail'
export default {
  components: {
    NormalDetail,
    SelectChildBank,
  },
  props: {},
  data() {
    return {
      queryDate: [],
      queryDate2: [],
      queryDate3: [],
      params: {
        'loan_approval_status.eq': 3,
        'confuse_status.neq': 3,
        'is_history.eq': 0,
        'gua_type.eq': 4,
        groupFields: ['service_id', 'gua_service_id', 'bank_id'],
        fields: [
          'service_id',
          'bank_id',
          'gua_service_id',
          'service_name',
          'gua_service_name',
          'recommend_service_name',
          'is_pro_dir',
          'bank_name',
        ],
        groupFunc: 'count(customer_related.customer_related_id),round(sum(reply_funds)|2)',
      },
      loading: false,
      tableName: 'customer_related',
      tableColumns: [
        { attrs: { label: '放款银行', prop: 'bank_name' } },
        { attrs: { label: '担保机构', prop: 'service_name' } },
        { attrs: { label: '联保机构', prop: 'gua_service_name' } },
        { attrs: { label: '项目数', prop: 'p' } },
        { attrs: { label: '担保金额', prop: 'p1' } },
      ],
      tableData: [],
      viewVisible: false,
      otherParams: {},

      tableCount: 0,
      tableFunds: 0,
      countLoading: false,
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    clientOrgClassType() {
      return this.user.clientOrgClassType
    },
  },
  watch: {},
  created() {
    this.getAllData()
  },
  mounted() {},
  methods: {
    selectRow(row) {
      this.otherParams = {
        ...this.params,
        groupFields: '',
        fields: '',
        groupFunc: '',
        'service_id.eq': row.service_id,
        'bank_id.eq': row.bank_id,
        'gua_service_id.eq': row.gua_service_id,
      }
      this.viewVisible = true
    },
    getAllData() {
      if (!this.queryAddressCode) {
        this.$message.error('机构配置出错，未添加机构地址')
        throw new Error('该机构没有地址')
      } else {
        this.params = {
          ...this.params,
          orWhereAndTemplate: 2,
          'orWhereAnd.bank_id.eq': this.clientId,
          'orWhereAnd.bank_type.in': this.clientOrgClassType,
          'orWhereAnd.address_code.gt': this.queryAddressCode,
          'orWhereAnd.address_code.lt': getAddressNextValue(this.queryAddressCode),
          'orWhereAnd.bank_type.eq': this.clientOrgClassType,
        }
      }
      this.getData()
      this.getCountData()
    },
    getCountData() {
      this.$api
        .getData(
          'credit',
          this.tableName,
          { ...this.params, groupFields: '' },
          { bank_type: 'asc' }
        )
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.tableCount = data.p || 0
          this.tableFunds = data.p1 || 0
        })
    },
    getData() {
      this.loading = true
      this.$api
        .getData('credit', this.tableName, this.params, { create_time: 'desc' })
        .then(res => {
          this.tableData = (res?.data ?? []).map(item => {
            if (+item.is_pro_dir === 1) {
              item.gua_service_name = '(省直业务)'
            } else {
              item.gua_service_name = item.gua_service_name || item.recommend_service_name
            }
            return item
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDateQuery3() {
      this.params['load_end_date.gte'] = ''
      this.params['load_end_date.lt'] = ''
      if (!this.queryDate3 || !this.queryDate3.length) {
        this.getAllData()
        return
      }
      let startTime = ''
      let endTime = ''
      const date = new Date(this.queryDate3[0])
      startTime = date
        ? `${date.getFullYear()}-${(date.getMonth() + 1 + '').padStart(2, 0)}-01`
        : ''
      endTime = date
        ? `${new Date(this.queryDate3[1]).getFullYear()}-${(
            new Date(this.queryDate3[1]).getMonth() +
            2 +
            ''
          ).padStart(2, 0)}-01`
        : ''

      this.params['load_end_date.gte'] = startTime
      this.params['load_end_date.lt'] = endTime
      this.getAllData()
    },
    handleDateQuery2() {
      this.params['load_date.gte'] = ''
      this.params['load_date.lt'] = ''
      if (!this.queryDate2 || !this.queryDate2.length) {
        this.getAllData()
        return
      }
      let startTime = ''
      let endTime = ''
      const date = new Date(this.queryDate2[0])
      startTime = date
        ? `${date.getFullYear()}-${(date.getMonth() + 1 + '').padStart(2, 0)}-01`
        : ''
      endTime = date
        ? `${new Date(this.queryDate2[1]).getFullYear()}-${(
            new Date(this.queryDate2[1]).getMonth() +
            2 +
            ''
          ).padStart(2, 0)}-01`
        : ''

      this.params['load_date.gte'] = startTime
      this.params['load_date.lt'] = endTime
      this.getAllData()
    },
    handleDateQuery() {
      this.params['create_time.gte'] = ''
      this.params['create_time.lt'] = ''
      if (!this.queryDate || !this.queryDate.length) {
        this.getAllData()
        return
      }
      let startTime = ''
      let endTime = ''
      const date = new Date(this.queryDate[0])
      startTime = date
        ? `${date.getFullYear()}-${(date.getMonth() + 1 + '').padStart(2, 0)}-01`
        : ''
      endTime = date
        ? `${new Date(this.queryDate[1]).getFullYear()}-${(
            new Date(this.queryDate[1]).getMonth() +
            2 +
            ''
          ).padStart(2, 0)}-01`
        : ''

      this.params['create_time.gte'] = startTime
      this.params['create_time.lt'] = endTime
      this.getAllData()
    },
  },
}
</script>

<style lang="scss" scoped></style>
